package com.i72.basic.init;

import com.i72.basic.consts.Consts;
import com.i72.basic.context.GlobalContext;
import com.i72.basic.enums.EnvironmentEnum;
import com.i72.basic.tools.BeanHelper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.util.List;
import java.util.Map;

@Component
public class GlobalConfigInit implements BeanFactoryAware, Ordered {


    private String getAddress(){
        if(getEnvironment().name().equals(EnvironmentEnum.LOCAL.name())) {
            try {
                return InetAddress.getLocalHost().getHostAddress();
            } catch (Exception e) {
                return "";
            }
        }else{
            return "";
        }
    }



    private EnvironmentEnum getEnvironment(){

        //依赖环境变量里的值来判定所处环境

        //StandardEnvironment e = (StandardEnvironment)this.applicationContext.getEnvironment();

        //Map m = e.getSystemEnvironment();

        Map m = System.getenv();

        if(m.containsKey(Consts.ENVIRONMENT_TYPE)){

            Object value = m.get(Consts.ENVIRONMENT_TYPE);
            if(value!=null && !StringUtils.isEmpty(value.toString())){
                String v = value.toString();

                if(v.equals(EnvironmentEnum.DEV.name())){
                    return EnvironmentEnum.DEV;
                }
                if(v.equals(EnvironmentEnum.TEST.name())){
                    return EnvironmentEnum.TEST;
                }
                if(v.equals(EnvironmentEnum.PRE.name())){
                    return EnvironmentEnum.PRE;
                }
                if(v.equals(EnvironmentEnum.PRO.name())){
                    return EnvironmentEnum.PRO;
                }
            }
            return EnvironmentEnum.LOCAL;

        }else{
            return EnvironmentEnum.LOCAL;
        }
    }


    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

        GlobalContext.setIP(getAddress());
        //GlobalContext.setPort(serviceNode.getPort());
        GlobalContext.setEnvironment(getEnvironment().name());


    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
